package com.colt.contentcenter.config.rule;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: content-center
 * @description: 配置nacos使用ribbon权重
 * @author: colt
 * @create: 2020-05-04 17:57
 **/
@Slf4j
public class NacosWeightedRuleConfig extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override//读取配置文件并初始化配置类
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {
        //loadBalancer Ribbon的入口
        BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
        //log.info("loadBalancer:{}", loadBalancer);
        loadBalancer.getName();//想要请求微服务的名称
        //实现负载均衡算法
        //拿到服务发现的相关API
        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
        try {
            //nacos client自动通过自身权重的复杂均衡算法，来选择一个实例
            Instance instance = namingService.selectOneHealthyInstance("user-center");
            log.info("选择的实例:port = {}，instance = {}",instance.getPort(),instance.getInstanceId());
            NacosServer nacosServer = new NacosServer(instance);
            return nacosServer;
        } catch (NacosException e) {
            return null;
        }
    }
}
